#include "front/front_interface.h"

using namespace std;
using namespace ppspeech;


vector<vector<string>> FrontEngineInterface::MergeErhua(const vector<string> &initials, const vector<string> &finals, const string &word, const string &pos)
{
	vector<string> new_initials = {};
	vector<string> new_finals = {};
	vector< vector<string> > new_initials_finals;
	vector<string> specified_pos = {"a", "j", "nr"};
	wstring word_wstr = ppspeech::utf8string2wstring(word);
	vector<wstring> wordvec;
	// 一个词转成向量形式
	if (0 != Word2WordVec(word, &wordvec)) {
		printf("ERROR: Frontend: Failed to get word vector\n");
	}
	int word_num = wordvec.size();

	if(  ( find(must_erhua.begin(), must_erhua.end(), word) == must_erhua.end() ) &&
		 ( (find(not_erhua.begin(), not_erhua.end(), word) != not_erhua.end()) || (find(specified_pos.begin(), specified_pos.end(), pos) != specified_pos.end()) )
		) {
		new_initials_finals.push_back(initials);
		new_initials_finals.push_back(finals);
		return new_initials_finals;
	}
	if (finals.size() != word_num) {
		new_initials_finals.push_back(initials);
		new_initials_finals.push_back(finals);
		return new_initials_finals;
	}

	assert(finals.size() == word_num);
	for(int i = 0; i < finals.size(); i++) {
		if(i == finals.size() - 1 && wordvec[i] == L"儿" &&
			(finals[i] == "er2" || finals[i] == "er5") && word_num >= 2 &&
			find(not_erhua.begin(), not_erhua.end(), ppspeech::wstring2utf8string( word_wstr.substr(word_wstr.length() - 2) )) == not_erhua.end() && !new_finals.empty()
			) {
			const string tcMergeFinal = new_finals.back().substr(0, new_finals.back().length() - 1) + "r" + new_finals.back().substr(new_finals.back().length() - 1);
			cout << tcMergeFinal << endl;
			
			if( mPhonemeIndexMap.find(tcMergeFinal) == mPhonemeIndexMap.end() ) {	//合并儿化后的韵母不在音素表中，则保留原先
				new_initials.push_back(initials[i]);
				new_finals.push_back(finals[i]);
			}
			else {
				new_finals.back() = tcMergeFinal;
			}
		}
		else {
			new_initials.push_back(initials[i]);
			new_finals.push_back(finals[i]);
		}
	}
	new_initials_finals.push_back(new_initials);
	new_initials_finals.push_back(new_finals);

	return new_initials_finals;
}
